import 'dart:math';

import 'package:fancy_shimmer_image/fancy_shimmer_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:provider/provider.dart';
import 'package:qianyi/entity/home/AlbumEntity.dart';
import 'package:qianyi/entity/home/album_detail_list_entity.dart';
import 'package:qianyi/network/http_manager.dart';
import 'package:qianyi/view_model/home/trend_view_model.dart';

import '../../../../controller/homeTabController.dart';
import '../../../../controller/imageDetailVideoController.dart';
import '../../../../entity/tags/Item.dart';
import '../../../../network/http_config.dart';
import '../../../../network/http_entity.dart';
import '../../../../state/token.dart';
import '../../../../ui/widget/custom_refresh.dart';
import '../../../../utils/throttle.dart';
import '../../../../view_model/home/AlbumDetailListModel.dart';
import '../../../../view_model/home/tags/TagsDetailListModel.dart';
import '../../../../view_model/mine/album_view_model.dart';
import '../../../../wcao/ui/theme.dart';


class TagsScreen extends StatefulWidget {
  @override
  _AlbumScreenState createState() => _AlbumScreenState();
}

class _AlbumScreenState extends State<TagsScreen> {
  HomeTabController homeTabController = Get.find();
  CategoryItem? albumEntity;
  bool isFinish = false;
  List<String> images = [
    'https://example.com/image1.jpg', // 替换为实际图片链接
    'https://example.com/image2.jpg', // 替换为实际图片链接
    // 添加更多图片链接...
  ];
  List<String> tabs = ["最新","最热"];
@override
  void initState() {

    // TODO: implement initState
    super.initState();
    getAlbumEntity();
  }
  getAlbumEntity() async {
  HudUtil.showBeautiful(context);
    Map<String,String> params1 = {
      "id":homeTabController.tagDetailId!,
    };

    HttpEntity httpEntity1 = await HttpManager.getInstance().request(url: '/platform/tag/getOneTag/',params: params1,method: Method.get) as HttpEntity;

    setState(() {
      albumEntity = CategoryItem.fromJson(httpEntity1.getOriData()['data']);
      this.isFinish = true;
    });
    HudUtil.dismiss();
  }
  @override
  Widget build(BuildContext context) {
    return isFinish? DefaultTabController(
        length: tabs.length,
        child: Scaffold(

          body: albumEntity!=null?SafeArea(

              child: NestedScrollView(
                physics: NeverScrollableScrollPhysics(),

                headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
                  return <Widget>[
                    // 可替换成 SliverPinnedHeader
                    SliverAppBar(
                      actions: [
                        IconButton(onPressed: (){
                          // 使用Navigator的popUntil方法返回到根路由
                          Navigator.of(context).popUntil((route) => route.isFirst);
                        }, icon: Icon(Icons.home_outlined))
                      ],
                      primary: false,
                      pinned: true,
                      toolbarHeight: 25,
                      title: Text("${albumEntity!.name!}"),
                      collapsedHeight: 25,
                      expandedHeight: 150,
                      bottom: TabBar(
                        padding: EdgeInsets.symmetric(horizontal: 60),
                        indicatorColor: WcaoTheme.primary,
                        indicatorSize: TabBarIndicatorSize.tab,
                        unselectedLabelColor: WcaoTheme.indexBootBarColor,
                        unselectedLabelStyle: const TextStyle(fontWeight: FontWeight.normal),
                        labelColor: WcaoTheme.indexBootBarActColor,
                        labelStyle: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        ),

                        indicatorWeight: 2,
                        indicatorPadding: const EdgeInsets.symmetric(horizontal: 45),
                        tabs: tabs
                            .map((e) => Tab(
                          text: e,
                        ))
                            .toList(),
                      ),
                    ),

                  ];
                },
                body: TabBarView(
                  physics: NeverScrollableScrollPhysics(),
                  children: [

                    buildWateFall(),
                    buildWateFall1()
                    // PageViewFound()
                  ],
                ) ,
              )):Text(""),
        )):Container()
      ;
  }

  double getRandomHeight() {
    // 生成一个随机高度
    double height = Random().nextDouble() * (200 - 80) + 168;
    return   height ;
  }
  buildWateFall() {
    TokenController tokenController = Get.find();

    ImageDetailVideoController imageDetailVideoController = Get.find<ImageDetailVideoController>();
    return ChangeNotifierProvider(
      create: (context) => TagsDetailListModel(),
        child: Consumer<TagsDetailListModel>(
            builder: (context, viewModel, child) {
              ;
              return

                CustomRefresh(
                    physics: NeverScrollableScrollPhysics(),
                    isMaterialHeader:true,
                    controller: viewModel.refreshController,
                    enablePullUp: true,
                    enablePullDown: true,
                    onRefresh: () async {
                      viewModel.onRefresh();
                    },
                    onLoading: () async {
                      viewModel.onLoading();
                    },
                    child:SingleChildScrollView(
                      child: MasonryGridView.count(
                        padding: EdgeInsets.all(0),
                        // 展示几列
                        crossAxisCount: 2,
                        // 元素总个数
                        itemCount: viewModel.datas.length,
                        // 单个子元素
                        itemBuilder: (BuildContext context, int index) {
                          TagItem trendEntity = viewModel.datas[index];
                          // var imgsUrl = jsonDecode(trendEntity.imgsUrl as String);
                          return GestureDetector(
                            onTap: () async {

                              HudUtil.showBeautiful(context);
                              String uid = await tokenController.getUid();
                              Map<String,dynamic> params = {
                                "mid":trendEntity!.id,
                                "uid": uid
                              };
                              HttpManager.getInstance().request(url: '/platform/browseRecord/addBrowseRecord',method: Method.post,params: params);
                              imageDetailVideoController.imageDetailId.value = trendEntity!.id!;
                              await imageDetailVideoController.getImageVideoDetail();
                              HudUtil.dismiss();
                              Get.toNamed("/ui/home/imageVideoDetail");

                            },
                            child: Card(
                              margin: EdgeInsets.all(1.5),

                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(4.0),
                                child:  Column(
                                  children: [
                                    FancyShimmerImage(
                                      height: getRandomHeight(),
                                      imageUrl: trendEntity.cover!,
                                    ),

                                    Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [

                                        Flexible(

                                          child: Text(
                                            trendEntity.content as String,maxLines: 2,softWrap: true, // 允许文本在超出最大行数时以省略号结束
                                            overflow: TextOverflow.ellipsis, style: TextStyle(fontWeight: FontWeight.w400),// 设置文本左对齐
                                          ),

                                        ),




                                      ],
                                    )

                                    ,
                                    Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        Row(
                                          children: [
                                            ClipOval(
                                                child: FancyShimmerImage(imageUrl: trendEntity.avatar as String,width: 20,height: 20,)
                                            ),

                                            Text(trendEntity.username as String),
                                          ],
                                        ),
                                        Row(
                                          children: [
                                            Icon(
                                              CupertinoIcons.heart,size: 14,
                                              color: Colors.grey,),
                                            Text(trendEntity.agreeCount as String)
                                          ],
                                        )
                                      ],
                                    )

                                  ],
                                ),
                              ),
                            ),
                          );
                        },

                        // 纵向元素间距
                        mainAxisSpacing: 0,
                        // 横向元素间距
                        crossAxisSpacing: 0,
                        //本身不滚动，让外面的singlescrollview来滚动
                        physics:const NeverScrollableScrollPhysics(),
                        shrinkWrap: true, //收缩，让元素宽度自适应
                      ),
                    )
                );
            }),
    )
      ;



  }
  buildWateFall1() {
    TokenController tokenController = Get.find();

    ImageDetailVideoController imageDetailVideoController = Get.find<ImageDetailVideoController>();
    return ChangeNotifierProvider(
      create: (context) => TagsDetailListModel1(),
      child: Consumer<TagsDetailListModel1>(
          builder: (context, viewModel, child) {
            return
              CustomRefresh(
                  isMaterialHeader:true,
                  controller: viewModel.refreshController,
                  enablePullUp: true,
                  enablePullDown: true,
                  onRefresh: () async {
                    viewModel.onRefresh();
                  },
                  onLoading: () async {
                    viewModel.onLoading();
                  },
                  child:SingleChildScrollView(
                    child: MasonryGridView.count(
                      padding: EdgeInsets.all(0),
                      // 展示几列
                      crossAxisCount: 2,
                      // 元素总个数
                      itemCount: viewModel.datas.length,
                      // 单个子元素
                      itemBuilder: (BuildContext context, int index) {
                        TagItem trendEntity = viewModel.datas[index];
                        // var imgsUrl = jsonDecode(trendEntity.imgsUrl as String);
                        return GestureDetector(
                          onTap: () async {

                            HudUtil.showBeautiful(context);
                            String uid = await tokenController.getUid();
                            Map<String,dynamic> params = {
                              "mid":trendEntity!.id,
                              "uid": uid
                            };
                            HttpManager.getInstance().request(url: '/platform/browseRecord/addBrowseRecord',method: Method.post,params: params);
                            imageDetailVideoController.imageDetailId.value = trendEntity!.id!;
                            await imageDetailVideoController.getImageVideoDetail();
                            HudUtil.dismiss();
                            Get.toNamed("/ui/home/imageVideoDetail");

                          },
                          child: Card(
                            margin: EdgeInsets.all(1.5),

                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(4.0),
                              child:  Column(
                                children: [
                                  FancyShimmerImage(
                                    height: getRandomHeight(),
                                    imageUrl: trendEntity.cover!,
                                  ),

                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [

                                      Flexible(

                                        child: Text(
                                          trendEntity.content as String,maxLines: 2,softWrap: true, // 允许文本在超出最大行数时以省略号结束
                                          overflow: TextOverflow.ellipsis, style: TextStyle(fontWeight: FontWeight.w400),// 设置文本左对齐
                                        ),

                                      ),




                                    ],
                                  )

                                  ,
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      Row(
                                        children: [
                                          ClipOval(
                                              child: FancyShimmerImage(imageUrl: trendEntity.avatar as String,width: 20,height: 20,)
                                          ),

                                          Text(trendEntity.username as String),
                                        ],
                                      ),
                                      Row(
                                        children: [
                                          Icon(
                                            CupertinoIcons.heart,size: 14,
                                            color: Colors.grey,),
                                          Text(trendEntity.agreeCount as String)
                                        ],
                                      )
                                    ],
                                  )

                                ],
                              ),
                            ),
                          ),
                        );
                      },

                      // 纵向元素间距
                      mainAxisSpacing: 0,
                      // 横向元素间距
                      crossAxisSpacing: 0,
                      //本身不滚动，让外面的singlescrollview来滚动
                      physics:const NeverScrollableScrollPhysics(),
                      shrinkWrap: true, //收缩，让元素宽度自适应
                    ),
                  )
              );
          }),
    )
    ;



  }

}
class CategoryItem {
  String id;
  String? creator;
  String? createDate;
  String count;
  String name;
  String? sort;

  CategoryItem({
    required this.id,
    this.creator,
    this.createDate,
    required this.count,
    required this.name,
    this.sort,
  });

  factory CategoryItem.fromJson(Map<String, dynamic> json) {
    return CategoryItem(
      id: json['id'],
      creator: json['creator'],
      // createDate: json['createDate'] as String,
      count: json['count'],
      name: json['name'],
      sort: json['sort'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'creator': creator,
      'createDate': createDate,
      'count': count,
      'name': name,
      'sort': sort,
    };
  }
}
